import asyncio
import os
import re
import time
from .utils import mylogger
from .clip2video import create_video_from_images_and_audio
from .ppt2audio import ppt_note_to_audio
from pptflow.config.setting import Setting
from pptflow.ppt2image_factory import get_ppt_to_image

# 创建日志纪录实例
logger = mylogger.get_logger(__name__)
ppt_to_image = get_ppt_to_image()


def ppt_to_video(tts, ppt_path, setting: Setting, progress_tracker=None):
    """
    Convert a PowerPoint presentation to a video with audio narration.
    
    Args:
        tts: The TTS service instance to use for generating audio
        ppt_path: Path to the PowerPoint file
        setting: Application settings
        progress_tracker: Optional progress tracker for UI updates
    """
    try:
        # Validate input parameters
        if tts is None:
            error_msg = "TTS service is not initialized. Please check your TTS service configuration."
            logger.error(error_msg)
            raise ValueError(error_msg)
            
        if ppt_path is None or not os.path.exists(ppt_path):
            error_msg = f"Invalid or missing PowerPoint file: {ppt_path}"
            logger.error(error_msg)
            raise FileNotFoundError(error_msg)

        # Set default output path if not specified
        if setting.video_path is None:
            setting.video_path = re.sub(r"(pptx?|pdf)$", setting.video_format.lower(), ppt_path)
            logger.info(f'Output video will be saved to: {setting.video_path}')

        # Record the start time for performance measurement
        start_time = time.time()

        # Step 1: Convert PPT to images
        if progress_tracker:
            progress_tracker.start_step('ppt_to_image')
        try:
            ppt_to_image.convert(ppt_path, setting, progress_tracker)
            logger.info(f"PPT to image conversion completed successfully")
        except Exception as e:
            error_msg = f"Failed to convert PPT to images: {str(e)}"
            logger.error(error_msg, exc_info=True)
            raise RuntimeError(error_msg) from e
        finally:
            if progress_tracker:
                progress_tracker.complete_step()

        end_time_ppt_to_image = time.time()
        logger.info(f"PPT to image conversion took: {end_time_ppt_to_image - start_time:.2f} seconds")

        # Step 2: Generate audio from notes using TTS
        if progress_tracker:
            progress_tracker.start_step('ppt_note_to_audio')
        try:
            logger.info(f"Starting audio generation with TTS service: {tts.__class__.__name__}")
            asyncio.run(ppt_note_to_audio(tts, ppt_path, setting, progress_tracker))
            logger.info("Audio generation completed successfully")
        except Exception as e:
            error_msg = f"Failed to generate audio: {str(e)}"
            logger.error(error_msg, exc_info=True)
            
            # Provide more helpful error message for TTS service issues
            if "fish_speech" in str(e).lower() or "8330" in str(e):
                error_msg += "\n\nIt seems you're trying to use Fish Speech TTS, but the service is not available. "
                error_msg += "Please ensure you have configured the correct TTS service in your .env file.\n"
                error_msg += "Example for CosyVoice V2:\n"
                error_msg += "TTS_SERVICE_PROVIDER=cosyvoice_v2\n"
                error_msg += "COSYVOICE_API_KEY=your_api_key_here"
                
            raise RuntimeError(error_msg) from e
        finally:
            if progress_tracker:
                progress_tracker.complete_step()

        end_time_ppt_note_to_audio = time.time()
        logger.info(f"Audio generation took: {end_time_ppt_note_to_audio - end_time_ppt_to_image:.2f} seconds")

        # Step 3: Create final video by combining images and audio
        if progress_tracker:
            progress_tracker.start_step('create_video')
        try:
            logger.info("Starting video creation...")
            create_video_from_images_and_audio(ppt_path, setting, progress_tracker)
            logger.info(f"Video creation completed successfully. Output: {setting.video_path}")
        except Exception as e:
            error_msg = f"Failed to create video: {str(e)}"
            logger.error(error_msg, exc_info=True)
            raise RuntimeError(error_msg) from e
        finally:
            if progress_tracker:
                progress_tracker.complete_step()

        logger.info(f"Total processing time: {time.time() - start_time:.2f} seconds")
        return setting.video_path
        
    except Exception as e:
        logger.error(f"Error in ppt_to_video: {str(e)}", exc_info=True)
        raise

    end_time_create_video = time.time()
    logger.info(f"create_video_from_images_and_audio runtime: {end_time_create_video - end_time_ppt_note_to_audio:.2f} seconds")

    # Total runtime
    total_time = end_time_create_video - start_time
    logger.info(f"Runtime: {total_time:.2f} seconds")
    return total_time
